package com.neteast.androidclient.contact.util;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.json.JSONException;
import org.json.JSONObject;

import com.neteast.androidclient.contact.R;
import com.neteast.androidclient.contact.domain.Contact;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.ThumbnailUtils;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.style.UpdateAppearance;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

public class ImageUtil{
	public static final String ACTION_IMAGE_HAS_DOWN = "action_image_has_down";
	private Contact contact;
	private ImageView imageView;
	private static HashMap<Integer, SoftReference<Bitmap>> imageCache;
	private Context context;
	private Drawable drawable;
	private static ImageUtil imageUtil;
	private int threadNum = 0;
	
	public static ImageUtil getInstance(Context context) {
		if (imageUtil==null) {
			imageUtil=new ImageUtil(context);
		}
		return imageUtil;
	}
	
	private ImageUtil(Context context) {
		this.context=context;
		imageCache=new HashMap<Integer, SoftReference<Bitmap>>();
		drawable = context.getResources().getDrawable(R.drawable.default_photo);
		
	}

	public void setImageView(Handler handler, Contact contact,ImageView imageView) {
		this.contact=contact;
		this.imageView=imageView;
		if(!contact.hasPhoto){
			imageView.setImageDrawable(drawable);
			return;
		}
		if (imageCache.containsKey(contact.contactId)) {
			Bitmap bitmap = imageCache.get(contact.contactId).get();
			if (bitmap!=null) {
				imageView.setImageBitmap(bitmap);
				imageView.setVisibility(View.VISIBLE);
				return;
			}
		}
		//内存里没有， 从文件里读取，并放入内存缓存
		//是通讯录好友，且本地有缓存
		String photo = getPhoto(context, contact.contactId);
		if (photo!=null) {
			File imageFile = new File(photo);
			if (!contact.isReadOnly) {
				if (imageFile.length()>0) {
					Bitmap bitmap =ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(imageFile.getAbsolutePath()), 64, 64);
					if (bitmap!=null) {
						imageCache.put(contact.contactId, new SoftReference<Bitmap>(bitmap));
						imageView.setImageBitmap(bitmap);
						imageView.setVisibility(View.VISIBLE);
						return;
					}
				}
			} else {
				if (imageFile.exists()) {
					imageFile.delete();
				}
			}
		}
		//是云好友或者通讯录好友但是本地没缓存，每次都从网络上下载
		if (contact.photo.startsWith("http://")) {
			
			showImage(handler,contact, imageView);
			imageView.setVisibility(View.VISIBLE);
		}
	}
		
	private void showImage(Handler handler, Contact contact, ImageView imageView){
//			threadNum++;
//			if(threadNum < 128){
//				LoadImageTask loadImageTask = new LoadImageTask();
//				loadImageTask.execute(contact,imageView);
//			}
		loadImg(handler, contact, imageView);
	}
	
	public class LoadImageTask extends AsyncTask<Object, Integer, Bitmap> {

		private Contact contact;
		private ImageView imageView;

		@Override
		protected Bitmap doInBackground(Object... params) {
			try {
			contact=(Contact)params[0];
			imageView = (ImageView) params[1];
			File saveFile = FileUtil.createPhotoFile(context);
			FileOutputStream fos=new FileOutputStream(saveFile);
			URL url=new URL(contact.photo);
			HttpURLConnection conn=(HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5*1000);
			conn.setRequestMethod("GET");
			Bitmap bitmap=BitmapFactory.decodeStream(conn.getInputStream());
			bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
			imageCache.put(contact.contactId, new SoftReference<Bitmap>(bitmap));
			setPhoto(context, contact.contactId, saveFile.getAbsolutePath());
			return bitmap;
			} catch (Exception e) {
				return null;
			}
		}
		
		@Override
		protected void onPostExecute(Bitmap result) {
				imageView.setImageBitmap(result);
				threadNum--;
		}
	}
	ExecutorService threadPoll = Executors.newFixedThreadPool(5);  
	public void loadImg(final Handler handler, final Contact contact,
			final ImageView imageViewfinal) {
		threadPoll.submit(new Runnable() {

			public void run() {
				try {
					File saveFile = FileUtil.createPhotoFile(context);
					FileOutputStream fos = new FileOutputStream(saveFile);
					URL url = new URL(contact.photo);
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setConnectTimeout(5 * 1000);
					conn.setRequestMethod("GET");
					final Bitmap bitmap = BitmapFactory.decodeStream(conn
							.getInputStream());
					bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
					imageCache.put(contact.contactId,
							new SoftReference<Bitmap>(bitmap));
					setPhoto(context, contact.contactId,
							saveFile.getAbsolutePath());
					Thread.currentThread().sleep(2000);
					handler.post(new Runnable() {
						public void run() {
							imageViewfinal.setImageBitmap(bitmap);
						}
					});
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 设置联系人头像的本地缓存地址
	 * @param context
	 * @param id
	 * @param file
	 */
	public static void setPhoto(Context context,int id,String filePath){
		SharedPreferences sp = context.getSharedPreferences("photo", Context.MODE_PRIVATE);
		Editor edit = sp.edit();
		edit.putString(""+id, filePath);
		edit.commit();
	}
	/**
	 * 获取联系人头像本地缓存地址
	 * @param context
	 * @param id
	 * @return
	 */
	public static String getPhoto(Context context,int id) {
		SharedPreferences sp = context.getSharedPreferences("photo", Context.MODE_PRIVATE);
		return sp.getString(""+id, null);
	}
}
